#执行命令如: sh /home/ec2-user/deploy.sh restart uptrade-gateway qa

#!/bin/bash

ACTION=$1
APP_NAME=$2  # jar包
ENV=$3  # JAVA spring.profiles.active

JAR_NAME="$APP_NAME.jar" # jar包的名字
APP_PATH=/home/ec2-user #所有的应用放在ec2-user用户下当前应用的目录下
PID_FILE=${APP_PATH}/${APP_NAME}/pid   # 应用的pid会保存到这个文件中

echo "ACTION: $ACTION, APP_NAME: $APP_NAME, ENV: $ENV, JAR_NAME: $JAR_NAME, APP_PATH: $APP_PATH"

start() {
    echo "start ${APP_PATH}/${JAR_NAME}"
    if [ -f "$PID_FILE" ] && kill -0 "$(cat ${PID_FILE})"; then
        echo "Application is running, exit"
        exit 0
    fi

    java -jar ${APP_PATH}/${APP_NAME}/${JAR_NAME} --spring.profiles.active=${ENV} >/dev/null 2>&1 &
    echo $! > ${PID_FILE}
}


stop() {
    echo "stop ${APP_PATH}/${JAR_NAME}"
    if [ -f "$PID_FILE" ]; then
        kill -9 `cat $PID_FILE`
        rm $PID_FILE
    else
        echo "pid file $PID_FILE does not exist, do noting"
    fi
}

case "$ACTION" in
    start)
        start
    ;;
    stop)
        stop
    ;;
    restart)
        stop
        start
    ;;
esac
